<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- 
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License. 
-->
<html>
<head>
    <link type="text/css" rel="stylesheet" href="https://struts.apache.org/css/default.css">
    <style type="text/css">
        .dp-highlighter {
            width:95% !important;
        }
    </style>
    <style type="text/css">
        .footer {
            background-image:      url('https://cwiki.apache.org/confluence/images/border/border_bottom.gif');
            background-repeat:     repeat-x;
            background-position:   left top;
            padding-top:           4px;
            color:                 #666;
        }
    </style>
    <link href='https://struts.apache.org/highlighter/style/shCoreStruts.css' rel='stylesheet' type='text/css' />
    <link href='https://struts.apache.org/highlighter/style/shThemeStruts.css' rel='stylesheet' type='text/css' />
    <script src='https://struts.apache.org/highlighter/js/shCore.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushPlain.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushXml.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushJava.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushJScript.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushGroovy.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushBash.js' type='text/javascript'></script>
    <script type="text/javascript">
        SyntaxHighlighter.defaults['toolbar'] = false;
        SyntaxHighlighter.all();
    </script>
    <script type="text/javascript" language="javascript">
        var hide = null;
        var show = null;
        var children = null;

        function init() {
            /* Search form initialization */
            var form = document.forms['search'];
            if (form != null) {
                form.elements['domains'].value = location.hostname;
                form.elements['sitesearch'].value = location.hostname;
            }

            /* Children initialization */
            hide = document.getElementById('hide');
            show = document.getElementById('show');
            children = document.all != null ?
                    document.all['children'] :
                    document.getElementById('children');
            if (children != null) {
                children.style.display = 'none';
                show.style.display = 'inline';
                hide.style.display = 'none';
            }
        }

        function showChildren() {
            children.style.display = 'block';
            show.style.display = 'none';
            hide.style.display = 'inline';
        }

        function hideChildren() {
            children.style.display = 'none';
            show.style.display = 'inline';
            hide.style.display = 'none';
        }
    </script>
    <title>Struts 2 Form Tags</title>
</head>
<body onload="init()">
<table border="0" cellpadding="2" cellspacing="0" width="100%">
    <tr class="topBar">
        <td align="left" valign="middle" class="topBarDiv" align="left" nowrap>
            &nbsp;<a href="home.html">Home</a>&nbsp;&gt;&nbsp;<a href="tutorials.html">Tutorials</a>&nbsp;&gt;&nbsp;<a href="getting-started.html">Getting Started</a>&nbsp;&gt;&nbsp;<a href="struts-2-form-tags.html">Struts 2 Form Tags</a>
        </td>
        <td align="right" valign="middle" nowrap>
            <form name="search" action="https://www.google.com/search" method="get">
                <input type="hidden" name="ie" value="UTF-8" />
                <input type="hidden" name="oe" value="UTF-8" />
                <input type="hidden" name="domains" value="" />
                <input type="hidden" name="sitesearch" value="" />
                <input type="text" name="q" maxlength="255" value="" />
                <input type="submit" name="btnG" value="Google Search" />
            </form>
        </td>
    </tr>
</table>

<div id="PageContent">
    <div class="pageheader" style="padding: 6px 0px 0px 0px;">
        <!-- We'll enable this once we figure out how to access (and save) the logo resource -->
        <!--img src="/wiki/images/confluence_logo.gif" style="float: left; margin: 4px 4px 4px 10px;" border="0"-->
        <div style="margin: 0px 10px 0px 10px" class="smalltext">Apache Struts 2 Documentation</div>
        <div style="margin: 0px 10px 8px 10px"  class="pagetitle">Struts 2 Form Tags</div>

        <div class="greynavbar" align="right" style="padding: 2px 10px; margin: 0px;">
            <a href="https://cwiki.apache.org/confluence/pages/editpage.action?pageId=19300595">
                <img src="https://cwiki.apache.org/confluence/images/icons/notep_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Edit Page"></a>
            <a href="https://cwiki.apache.org/confluence/pages/editpage.action?pageId=19300595">Edit Page</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/listpages.action?key=WW">
                <img src="https://cwiki.apache.org/confluence/images/icons/browse_space.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Browse Space"></a>
            <a href="https://cwiki.apache.org/confluence/pages/listpages.action?key=WW">Browse Space</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/createpage.action?spaceKey=WW&fromPageId=19300595">
                <img src="https://cwiki.apache.org/confluence/images/icons/add_page_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Add Page"></a>
            <a href="https://cwiki.apache.org/confluence/pages/createpage.action?spaceKey=WW&fromPageId=19300595">Add Page</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/createblogpost.action?spaceKey=WW&fromPageId=19300595">
                <img src="https://cwiki.apache.org/confluence/images/icons/add_blogentry_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Add News"></a>
            <a href="https://cwiki.apache.org/confluence/pages/createblogpost.action?spaceKey=WW&fromPageId=19300595">Add News</a>
        </div>
    </div>

    <div class="pagecontent">
        <div class="wiki-content">
            <div id="ConfluenceContent"><div class="confluence-information-macro confluence-information-macro-information"><span class="aui-icon aui-icon-small aui-iconfont-info confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>The example code for this tutorial, form_tags, can be checked out from <a shape="rect" class="external-link" href="https://github.com/apache/struts-examples" rel="nofollow">https://github.com/apache/struts-examples</a>.</p></div></div><h3 id="Struts2FormTags-Introduction">Introduction</h3><p>In this tutorial we'll explore some of the other Struts 2 form controls. In our previous tutorials that explained how to use Struts 2 forms (<a shape="rect" href="processing-forms.html">Processing Forms</a>, <a shape="rect" href="form-validation.html">Form Validation</a>, and <a shape="rect" href="message-resource-files.html">Message Resource Files</a>) we covered how to use the Struts 2 head, form, textfield controls and the key attribute. This tutorial will explore using the Struts 2 select, radio, checkbox, and checkboxlist form controls.</p><div class="confluence-information-macro confluence-information-macro-tip"><span class="aui-icon aui-icon-small aui-iconfont-approve confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>The <a shape="rect" class="external-link" href="http://struts.apache.org/mail.html">Struts 2 user mailing list</a> is an excellent place to get help. If you are having a problem getting the tutorial example applications to work search the Struts 2 mailing list. If you don't find an answer to your problem, post a question on the mailing list.</p></div></div><h3 id="Struts2FormTags-ExampleApplication">Example Application</h3><p>The example application that supports this tutorial shows how to use Struts 2 form tags so that a user can edit his information. The information that can be edited is encapsulated in an object of class Person. A Person object knows these things: first name, last name, favorite sport, gender, state of residency, is or is not over 21, and car models owned.</p><p>To enable the user to edit his information that is stored in the Person object, we need to create a form like this one:</p><p><span class="confluence-embedded-file-wrapper"><img class="confluence-embedded-image" src="struts-2-form-tags.data/Screen%20shot%202010-04-25%20at%208.39.59%20AM.png"></span></p><p>The form allows the user to make changes. After submitting the form, the Struts 2 framework will update the state of the Person object.</p><p>The first and last names are shown on the form (see edit.jsp) using the Struts 2 textfield tag, which we've discussed in previous tutorials.</p><h3 id="Struts2FormTags-Struts2SelectTag">Struts 2 Select Tag</h3><p>A user can select one favorite sport from several choices. The example application uses the Struts 2 select tag to provide the list of options for the select box.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>Struts 2 Select Tag</b></div><div class="codeContent panelContent pdl">
<pre class="brush: html; gutter: false; theme: Default" style="font-size:12px;">&lt;s:select key="personBean.sport" list="sports" /&gt;

</pre>
</div></div><p>In these form tags, we are using the key attribute as discussed in the <a shape="rect" href="message-resource-files.html">Message Resource Files</a> tutorial. The key attribute is used by the Struts 2 framework to determine values for the other attributes (e.g. label and value). We are also using a property file associated with the EditAction class to provide the label values based on the key attribute value (see the <a shape="rect" href="message-resource-files.html">Message Resource Files</a> tutorial for information on using Struts 2 property files).</p><div class="confluence-information-macro confluence-information-macro-information"><span class="aui-icon aui-icon-small aui-iconfont-info confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>Note that there are many attributes for the Struts 2 form tags, most of which mirror the HTML attributes associated with the tags. You can read about all the attributes for a Struts 2 form tag by consulting the Struts 2 documentation.</p></div></div><p>The value of the list attribute of the Struts 2 select tag is used by the framework to determine what method of the action class to call in order to create the option values. In our example application, the list attribute value of "sports" results in the framework calling the getSports method of class EditAction. That method returns a String array containing "football", "baseball", and "basketball". Those values are used to create the option tags inside the select tag.</p><p>The Struts 2 framework determines which option is preselected by using the key attribute's value to call a method on the personBean object. Since the key attribute's value is "personBean.sport", the framework calls the personBean object's getSport method. If the value returned by that method matches one of the option values, that option will be marked as "selected".</p><p>Here is the HTML that results from using the above Struts 2 select tag.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>HTML Created By Struts 2 Select Tag</b></div><div class="codeContent panelContent pdl">
<pre class="brush: html; gutter: false; theme: Default" style="font-size:12px;">&lt;tr&gt;
&lt;td class="tdLabel"&gt;
&lt;label for="save_personBean_sport" class="label"&gt;Favorite sport:&lt;/label&gt;
&lt;/td&gt;
&lt;td&gt;
&lt;select name="personBean.sport" id="save_personBean_sport"&gt;
    &lt;option value="football"&gt;football&lt;/option&gt;
    &lt;option value="baseball"&gt;baseball&lt;/option&gt;
    &lt;option value="basketball" selected="selected"&gt;basketball&lt;/option&gt;
&lt;/select&gt;
&lt;/td&gt;
&lt;/tr&gt;

</pre>
</div></div><p>Note the table formatting created by the Struts 2 framework when using the Struts 2 select tag. The CSS classes are defined in style sheets included by the Struts 2 s:head tag. The Struts 2 s:head tag is placed inside the edit.jsp's head section.</p><p>Since the personBean's getSport method returns "baskeball", the basketball option value is marked as selected.</p><h3 id="Struts2FormTags-Struts2RadioTag">Struts 2 Radio Tag</h3><p>The Struts 2 radio tag&#8212;like its standard HTML counterpart&#8212;is used to display 2 or more choices, only one of which can be selected by the user. Here is the code for the Struts 2 radio button from the example application.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>Struts 2 Radio Tag</b></div><div class="codeContent panelContent pdl">
<pre class="brush: html; gutter: false; theme: Default" style="font-size:12px;">&lt;s:radio key="personBean.gender" list="genders" /&gt;

</pre>
</div></div><p>Again the key attribute's value determines the value for the label and value attributes. The label's text is derived from the EditAction.properties file (key personBean.gender). Just like the Struts 2 select tag, the list attribute of the Struts 2 radio tag causes the framework to call the getGenders method of the EditAction class. The Array of String objects returned are used to create the individual radio buttons.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>HTML Created By Struts 2 Radio Tag</b></div><div class="codeContent panelContent pdl">
<pre class="brush: html; gutter: false; theme: Default" style="font-size:12px;">&lt;tr&gt;
&lt;td class="tdLabel"&gt;
&lt;label for="save_personBean_gender" class="label"&gt;Gender:&lt;/label&gt;&lt;/td&gt;
&lt;td&gt;
&lt;input type="radio" name="personBean.gender" id="save_personBean_gendermale" value="male"/&gt;&lt;label for="save_personBean_gendermale"&gt;male&lt;/label&gt;
&lt;input type="radio" name="personBean.gender" id="save_personBean_genderfemale" value="female"/&gt;&lt;label for="save_personBean_genderfemale"&gt;female&lt;/label&gt;
&lt;input type="radio" name="personBean.gender" id="save_personBean_gendernot sure" checked="checked" value="not sure"/&gt;&lt;label for="save_personBean_gendernot sure"&gt;not sure&lt;/label&gt;
&lt;/td&gt;
&lt;/tr&gt;

</pre>
</div></div><p>Also just like the Struts 2 select tag the result returned by calling the personBean object's getGender method is used to determine which of the radio buttons is checked.</p><h3 id="Struts2FormTags-Struts2SelectTag-ObjectBacked">Struts 2 Select Tag - Object Backed</h3><p>You may need to create a Struts 2 select tag where the options displayed to the user each have their own value that is different then what is displayed. In the example application, the user's residency is stored as a two-letter abbreviation (e.g. KS), but the form select box should display the full state name (e.g. Kansas). To create such a select box in Struts 2, you would use this code</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>Struts 2 Select Tag Object Backed</b></div><div class="codeContent panelContent pdl">
<pre class="brush: html; gutter: false; theme: Default" style="font-size:12px;">&lt;s:select key="personBean.residency" list="states" listKey="stateAbbr" listValue="stateName" /&gt;

</pre>
</div></div><p>The list value tells the framework to call the getStates method of the EditAction class. That method returns an ArrayList of State objects. Each State object has getStateAbbr and getStateName methods.</p><p>The listKey attribute tells the framework to use the value returned by calling the getStateAbbr method as the value for the value attribute of the HTML option tag and the value returned by calling the getStateName method as the value displayed to the user. So the above Struts 2 select tag code results in this HTML.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>HTML Created By Struts 2 Select Tag</b></div><div class="codeContent panelContent pdl">
<pre class="brush: html; gutter: false; theme: Default" style="font-size:12px;">&lt;tr&gt;
&lt;td class="tdLabel"&gt;
&lt;label for="save_personBean_residency" class="label"&gt;State resident:&lt;/label&gt;&lt;/td&gt;
&lt;td&gt;
&lt;select name="personBean.residency" id="save_personBean_residency"&gt;
    &lt;option value="AZ"&gt;Arizona&lt;/option&gt;
    &lt;option value="CA"&gt;California&lt;/option&gt;
    &lt;option value="FL"&gt;Florida&lt;/option&gt;
    &lt;option value="KS" selected="selected"&gt;Kansas&lt;/option&gt;
    &lt;option value="NY"&gt;New York&lt;/option&gt;
&lt;/select&gt;
&lt;/td&gt;
&lt;/tr&gt;

</pre>
</div></div><p>The value returned by calling the personBean object's getResidency method determines which of the select tag's option tags is marked as selected. In our example, since getResidency returns "KS", the option tag whose value attribute equals "KS" is marked as selected.</p><h3 id="Struts2FormTags-Struts2CheckboxTag">Struts 2 Checkbox Tag</h3><p>The Struts 2 checkbox tag is used to create the HTML input type equals checkbox tag. The value for the key attribute tells the framework what method to call to determine if the checkbox is checked or not checked. The method called should return a Boolean value (true or false). A return value of true will cause the checkbox to be checked and false the checkbox will not be checked.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>Struts 2 Checkbox Tag</b></div><div class="codeContent panelContent pdl">
<pre class="brush: html; gutter: false; theme: Default" style="font-size:12px;">&lt;s:checkbox key="personBean.over21" /&gt;

</pre>
</div></div><p>Since the method getOver21 returns true, the checkbox is checked.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>HTML Created By Struts 2 Checkbox Tag</b></div><div class="codeContent panelContent pdl">
<pre class="brush: html; gutter: false; theme: Default" style="font-size:12px;">&lt;tr&gt;
&lt;td valign="top" align="right"&gt;
&lt;/td&gt;
&lt;td valign="top" align="left"&gt;
&lt;input type="checkbox" name="personBean.over21" value="true" checked="checked" id="save_personBean_over21"/&gt;
&lt;input type="hidden" id="__checkbox_save_personBean_over21" name="__checkbox_personBean.over21" value="true" /&gt;  &lt;label for="save_personBean_over21" class="checkboxLabel"&gt;21 or older&lt;/label&gt;
&lt;/td&gt;
&lt;/tr&gt;

</pre>
</div></div><p>When the form is submitted and the checkbox is not checked, no value will be posted for the checkbox (this is how HTML forms work). Since the Struts 2 framework will need to update the value of the personBean's over21 instance field to false&#8212;given that the check box was not checked&#8212;the framework needs a way to determine if the checkbox was not checked after form submission.</p><p>If you examine the HTML code created by the Struts 2 checkbox tag, you'll see that it created a hidden field associated with the personBean.over21 checkbox. When the Struts 2 framework intercepts the submission of this form it will use this hidden form field to check if the associated checkbox field exists in the posted form data. If that checkbox field doesn't exist then the Struts 2 framework will know to update the value of the personBean object's over21 instance variable to false.</p><h3 id="Struts2FormTags-Struts2checkboxlistTag">Struts 2 checkboxlist Tag</h3><p>The Struts 2 framework provides a unique form field control that creates a series of associated check boxes, one or more of which can be checked. In the example application, the Person class has an Array of Strings, which is used to store car models owned by a person.</p><p>Using the Struts 2 checkbox tag, we can create a series of checkboxes, one for each possible car model the user may own. The value of each String in the personBean's carModels Array will determine which checkboxes are checked.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>Struts 2 Checkboxlist Tag</b></div><div class="codeContent panelContent pdl">
<pre class="brush: html; gutter: false; theme: Default" style="font-size:12px;">&lt;s:checkboxlist key="personBean.carModels" list="carModelsAvailable" /&gt;

</pre>
</div></div><p>The list attributes value in the checkboxlist tag tells the Struts 2 framework which method to call to get the possible car models. In the example application, the framework will call the EditAction class's getCarModelsAvailable method. That method returns an Array of Strings. For each element of the Array, the Struts 2 framework creates a checkbox (including the associated hidden field described above).</p><p>The key attribute value in the checkboxlist tag tells the Struts 2 framework which method to call on the personBean object to determine which checkboxes should be checked. In the example application, the framework will call the personBean object's getCarModels method. The getCarModels method returns an Array of Strings. For each String value in that Array that matches a String value in the Array returned by the EditAction class's getCarModelsAvailable, the checkbox will be checked.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>HTML Created By Struts 2 Checkboxlist Tag</b></div><div class="codeContent panelContent pdl">
<pre class="brush: html; gutter: false; theme: Default" style="font-size:12px;">&lt;tr&gt;
&lt;td class="tdLabel"&gt;
&lt;label for="save_personBean_carModels" class="label"&gt;Car models owned:&lt;/label&gt;&lt;/td&gt;
&lt;td&gt;
&lt;input type="checkbox" name="personBean.carModels" value="Ford" id="personBean.carModels-1" checked="checked"/&gt;
&lt;label for="personBean.carModels-1" class="checkboxLabel"&gt;Ford&lt;/label&gt;
&lt;input type="checkbox" name="personBean.carModels" value="Chrysler" id="personBean.carModels-2"/&gt;
&lt;label for="personBean.carModels-2" class="checkboxLabel"&gt;Chrysler&lt;/label&gt;
&lt;input type="checkbox" name="personBean.carModels" value="Toyota" id="personBean.carModels-3"/&gt;
&lt;label for="personBean.carModels-3" class="checkboxLabel"&gt;Toyota&lt;/label&gt;
&lt;input type="checkbox" name="personBean.carModels" value="Nissan" id="personBean.carModels-4" checked="checked"/&gt;
&lt;label for="personBean.carModels-4" class="checkboxLabel"&gt;Nissan&lt;/label&gt;
&lt;input type="hidden" id="__multiselect_save_personBean_carModels" name="__multiselect_personBean.carModels" value="" /&gt;
&lt;/td&gt;
&lt;/tr&gt;

</pre>
</div></div><p>Summary<br clear="none"> There are several other Struts 2 form controls you should explore. If you need more information about the Struts 2 form tags consult the Struts 2 documentation at <a shape="rect" class="external-link" href="http://struts.apache.org">http://struts.apache.org</a>.</p><h3 id="Struts2FormTags-UpNext">Up Next</h3><p>In our next tutorial we'll cover how to use XML to validate a user's form field entries.</p><div class="table-wrap"><table class="confluenceTable"><tbody><tr><th colspan="1" rowspan="1" class="confluenceTh"><p>Next</p></th><td colspan="1" rowspan="1" class="confluenceTd"><p>Onward to <a shape="rect" href="form-validation-using-xml.html">Form Validation Using XML</a></p></td></tr><tr><th colspan="1" rowspan="1" class="confluenceTh"><p>Prev</p></th><td colspan="1" rowspan="1" class="confluenceTd"><p>Return to <a shape="rect" href="debugging-struts.html">Debugging Struts</a></p></td></tr></tbody></table></div></div>
        </div>

        
    </div>
</div>
<div class="footer">
    Generated by CXF SiteExporter
</div>
</body>
</html>
